import pygame
import random
import sys
import math

pygame.init()

# 物体状态贴图
clear_image = pygame.image.load("clear.png")
wait_image = pygame.image.load("wait.png")
hit_image = pygame.image.load("hit.png")
center_image = pygame.image.load("center.png")

# 放大图像
center_image = pygame.transform.scale(center_image, (30, 30))
clear_image = pygame.transform.scale(clear_image, (356, 186))
wait_image = pygame.transform.scale(wait_image, (356, 186))
hit_image = pygame.transform.scale(hit_image, (356, 186))

# 物体状态
clear = 0
wait = 1
hit = 2


def initialize_objects():
    return [clear, clear, clear, clear, clear]


def draw_objects(objects, screen):
    for i, obj_color in enumerate(objects):
        obj_image = clear_image
        if obj_color == wait:
            obj_image = wait_image
        elif obj_color == hit:
            obj_image = hit_image

        obj_rect = obj_image.get_rect()
        obj_angle = angle + i * angle_increment
        obj_angle_radians = obj_angle * (math.pi / 180)  # 将角度转换为弧度
        obj_rotated_image = pygame.transform.rotate(obj_image, -obj_angle)  # 旋转图片

        # 计算旋转后的中心位置
        obj_center_offset = (
            (obj_rotated_image.get_width() - obj_image.get_width()) / 2,
            (obj_rotated_image.get_height() - obj_image.get_height()) / 2
        )
        obj_center = (
            center[0] + radius * pygame.math.Vector2(1, 0).rotate(obj_angle)[0] - obj_center_offset[0],
            center[1] + radius * pygame.math.Vector2(1, 0).rotate(obj_angle)[1] - obj_center_offset[1]
        )
        screen.blit(obj_rotated_image, obj_center)


def switch_colors(objects):
    wait_indices = [i for i, obj in enumerate(objects) if obj == wait]
    if wait_indices:
        objects[wait_indices[0]] = hit
        clear_indices = [i for i, obj in enumerate(objects) if obj == clear]
        if clear_indices:
            random_clear_index = random.choice(clear_indices)
            objects[random_clear_index] = wait
    else:
        clear_indices = [i for i, obj in enumerate(objects) if obj == clear]
        if clear_indices:
            random_clear_index = random.choice(clear_indices)
            objects[random_clear_index] = wait


# 初始化
objects = initialize_objects()

# 初始化屏幕
screen = pygame.display.set_mode((1200, 1000))
pygame.display.set_caption("能量机关")
font_name = pygame.font.match_font('SimHei')
font = pygame.font.Font(font_name, 25)
clock = pygame.time.Clock()

# 初始角度和旋转速度
angle = 0
rotation_speed = 60  # 初始旋转速度为60度每秒

# 图片中心修正
center_image_rect = center_image.get_rect(center=(400, 400))
center_image_offset = (
    center_image_rect.width / 2,
    center_image_rect.height / 2
)

# 游戏状态
GAME_RUNNING = 0
GAME_OVER = 1
game_state = GAME_RUNNING

# 交替状态的计数器
alternating_counter = 0

# 交替状态的计时器和间隔
alternating_timer = 0
alternating_interval = 10  # 间隔30帧（0.5秒）

# 定义目标函数参数范围
a_min = 0.780
a_max = 1.045
omega_min = 1.884
omega_max = 2.000

# 默认速度模式
linear_speed_mode = True


def reset_parameters():
    global rotation_speed, a, omega, b
    a = random.uniform(a_min, a_max)
    omega = random.uniform(omega_min, omega_max)
    b = 2.090 - a
    rotation_speed = 60 if linear_speed_mode else a * math.sin(omega * 0) + b


# 初始化时重置参数
reset_parameters()
check_time = pygame.time.get_ticks() / 1000
stat_check = False
# 游戏主循环
running = True
while running:
    screen.fill((0, 0, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE and game_state == GAME_RUNNING:
                switch_colors(objects)
                check_time = pygame.time.get_ticks() / 1000
                stat_check = True
            elif event.key == pygame.K_r and game_state == GAME_OVER:
                game_state = GAME_RUNNING
                objects = initialize_objects()
                alternating_counter = 0
                reset_parameters()  # 重新开始时重置参数
            elif event.key == pygame.K_RETURN:
                linear_speed_mode = not linear_speed_mode
                game_state = GAME_RUNNING
                objects = initialize_objects()
                reset_parameters()  # 切换速度模式时重置参数

    # 在游戏主循环中进行计时
    if game_state == GAME_RUNNING:
        # 计算物体位置
        radius = 230
        center = (400, 400)
        t = pygame.time.get_ticks() / 1000  # 获取时间（秒）

        if stat_check:
            if t - check_time > 2.5:  # 如果黄色物体超过2.5秒未被切换为红色
                objects = initialize_objects()
                alternating_counter = 0
                reset_parameters()  # 重新开始时重置参数
                stat_check = False

        # 计算物体位置
        # print(wait_timeout)
        radius = 230
        center = (400, 400)
        t = pygame.time.get_ticks() / 1000  # 获取时间（秒）
        rotation_speed = 60 if linear_speed_mode else (a * math.sin(omega * t) + b) * 57.29  # 计算新的旋转速度
        angle += rotation_speed / 60  # 更新角度
        angle %= 360  # 角度保持在 0 到 359 之间
        angle_increment = 360 / len(objects)
        draw_objects(objects, screen)

        # 绘制中心图像
        screen.blit(center_image, (560, 480))

        # 检查是否所有物体都变成了红色
        if all(obj == hit for obj in objects):
            game_state = GAME_OVER
        # 显示提示信息和当前速度模式
        mode_text = "小能量机关（按“回车”切换）" if linear_speed_mode else "大能量机关（按“回车”切换）"
        mode_surface = font.render(mode_text, True, (255, 255, 255))
        screen.blit(mode_surface, (850, 950))
        instruction_surface = font.render("按“空格”激活能量机关", True, (255, 255, 255))
        screen.blit(instruction_surface, (900, 920))

    elif game_state == GAME_OVER:

        radius = 230
        center = (400, 400)
        t = pygame.time.get_ticks() / 1000  # 获取时间（秒）
        rotation_speed = 60 if linear_speed_mode else (a * math.sin(omega * t) + b) * 57.29  # 计算新的旋转速度
        angle += rotation_speed / 60  # 更新角度
        angle %= 360  # 角度保持在 0 到 359 之间
        angle_increment = 360 / len(objects)
        # 在游戏结束时交替状态
        if alternating_timer < alternating_interval:
            # 计算物体位置
            alternating_timer += 1
        else:
            if alternating_counter < 18:
                if alternating_counter % 2 == 0:
                    objects = initialize_objects()
                else:
                    objects = [hit, hit, hit, hit, hit]
                alternating_counter += 1
                alternating_timer = 0
            else:
                text_surface = font.render("激活成功，按“R”重新激活", True, (255, 255, 255))
                screen.blit(text_surface, (850, 960))
        draw_objects(objects, screen)
        screen.blit(center_image, (560, 480))


    pygame.display.flip()
    clock.tick(60)  # 限制帧率为 60fps

pygame.quit()
sys.exit()
